// pages/route/airport/airport.js
const app = getApp();
const service = require('../../../utils/service.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 當前日期
    nowDate: app.utils.parseTime(new Date(), '{y}-{m}-{d}'),
    // 當前時間
    nowTime: '00:00',
    // 路线类型
    routeType: 1,
    // 收费模式
    chargeType: 1,
    // 接送机状态
    navIdx: 1,
    // 机场列表
    airport: [],
    // 机场id
    airportIdx: null,
    // 地点
    location: '',
    // 详细地址
    address: '',
    // 精度
    latitude: '',
    // 纬度
    longitude: '',
    // 预定日期
    date: null,
    // 预定时间
    time: null,
    // 举牌服务
    placards: 1,
    // 航班号
    flightNumber: null,
    // 车型列表
    carTypeList: [],
    // 选择的车idx
    carTypeIdx: 0,
    // 选择的联系人
    liaison: {},
    // 乘车人数
    rideNumber: 1,
    // 选择的优惠券
    coupon: null,
    // 最终价格
    finallyPrice: '--',
    // 备注
    memo: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    options.pageName && wx.setNavigationBarTitle({
      title: options.pageName,
    });

    if(options.params){
      this.setData(JSON.parse(options.params));
    }
    this.loadData();
  },

  // 加载机场信息
  loadData() {
    let that = this;
    let params = {
      type: this.data['navIdx']
    }
    service.getConnect(service.api.getAirportRouteData, params).then(function(res) {
      wx.hideLoading();
      that.setData(res.data);
      that.loadCarListAndPriceByParams();
    });
  },

  // 接送机选择
  bindTapNav(e) {
    this.setData({
      navIdx: parseInt(e.currentTarget.dataset.idx),
      airportIdx: null
    });
    this.loadData();
  },

  // 机场选择
  bindAirportChange(e) {
    this.setData({
      airportIdx: e.detail.value
    })
    this.loadCarListAndPriceByParams();
  },

  // 选择地点
  bindSelectAdress() {
    var that = this;
    wx.chooseLocation({
      success: res=>{
        console.log('=============选择地址===============')
        console.log(res);
        that.setData({
          location: res.name,
          address: res.address,
          latitude: res.latitude,
          longitude: res.longitude
        });
        that.loadCarListAndPriceByParams();
      }
    })
  },

  // 日期选择
  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    });
    console.log(e.detail.value, this.data.nowDate)
    if (e.detail.value === this.data.nowDate){
      this.setData({
        nowTime: app.utils.parseTime(new Date(), '{h}:{i}')
      })
    }
    this.loadCarListAndPriceByParams();
  },

  // 时间选择
  bindTimeChange(e) {
    this.setData({
      time: e.detail.value
    });
  },

  // 根据地址信息获取车辆类型及价格
  loadCarListAndPriceByParams() {
    let that = this;
    if (this.data['airportIdx'] !== null && this.data['locatiion'] !== '' &&
      this.data['date'] !== null) {
      let params = {
        lineId: this.data['airport'][this.data['airportIdx']]['lineId'],
        address: this.data['address'],
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        chooseTime: this.data['date']
      }
      service.getConnect(service.api.getAirportRouteCarAndPrice, params).then(function(res) {
        wx.hideLoading();
        that.setData({
          carTypeList: res.data,
          carTypeIdx: 0,
          chargeType: res.data[0]['chargeType'],
          finallyPrice: res.data[0]['chargeType'] === 0 ? parseFloat(res.data[0]['money']) * that.data['rideNumber']:parseFloat(res.data[0]['money'])
        });
      });
    }
  },

  // 举牌服务
  bindSwitchChange(e) {
    this.setData({
      placards: e.detail.value ? 2 : 1
    })
  },

  // 航班号输入
  bindFlightNumberInput(e){
    this.setData({
     flightNumber: e.detail.value
    })
  },

  // 选择车型
  bindCarTypeChange(e) {
    var that = this;
    this.setData({
      carTypeIdx: e.detail.value,
      chargeType: that.data['carTypeList'][e.detail.value]['chargeType'],
      finallyPrice: that.data['carTypeList'][e.detail.value]['chargeType'] === 0 ? parseFloat(this.data['carTypeList'][e.detail.value]['money']) * this.data['rideNumber'] : parseFloat(this.data['carTypeList'][e.detail.value]['money'])
    })
  },

  // 选择联系人
  bindSelectLiaison() {
    wx.navigateTo({
      url: '../../center/liaison/liaison?source=route',
    })
  },

  // 票数减少
  bindTicketCountDown() {
    var that = this;
    if (this.data['carTypeList'] && this.data['carTypeList'].length <= 0) {
      app.showConfirm('提示', '该区域未开通线路, 请检查路线地址', false);
      return;
    }
    if (this.data['rideNumber'] > 1) {
      this.setData({
        rideNumber: this.data['rideNumber'] - 1,
        coupon: null,
        finallyPrice: that.data.chargeType===0?(parseFloat(this.data['carTypeList'][this.data['carTypeIdx']]['money']) * (this.data['rideNumber'] - 1)) : that.data.finallyPrice
      })
    }
  },

  // 票数增加
  bindTicketCountUp(e) {
    var that = this;
    if (this.data['carTypeList'] && this.data['carTypeList'].length <= 0) {
      app.showConfirm('提示', '该区域未开通线路, 请检查路线地址', false);
      return;
    }
    if (this.data['rideNumber']<this.data.carTypeList[this.data.carTypeIdx].rideNumber-1) {
      this.setData({
        coupon: null,
        rideNumber: this.data['rideNumber'] + 1,
        finallyPrice: that.data.chargeType === 0 ? (parseFloat(this.data['carTypeList'][this.data['carTypeIdx']]['money']) * (this.data['rideNumber'] + 1)) : that.data.finallyPrice
      })
    }
  },

  // 备注输入
  bindMemoInput(e){
    this.setData({
      memo: e.detail.value
    })
  },

  // 选择优惠券
  toSelectCoupon() {
    let money = this.data.chargeType === 0 ? (parseFloat(this.data['carTypeList'][this.data['carTypeIdx']]['money']) * this.data['rideNumber']) : this.data.finallyPrice;
    wx.navigateTo({
      url: '/pages/route/selectCoupon/selectCoupon?money=' + money
        + '&type=' + this.data.routeType,
    })
  },

  // 立刻预定
  submitAirportRouteOrder(){
    let that = this;
    let data = this.data;
    if (data['airportIdx'] === null || data['address'] === null) {
      app.showConfirm('提示', '请选择出发地,目的地~', false);
      return;
    };
    if (data['date'] === null || data['time'] === null) {
      app.showConfirm('提示', '请选择航班到达时间~', false);
      return;
    };
    if (data.carTypeList.length <= 0) {
      app.showConfirm('提示', '该区域路线未开通~', false);
      return;
    }
    if (!data['carTypeList'][data['carTypeIdx']]['orderKey']) {
      app.showConfirm('提示', '请选择车辆类型~', false);
      return;
    };
    if (!data['liaison']['id']) {
      app.showConfirm('提示', '请选择联系人', false, function () {
        wx.navigateTo({
          url: '/pages/center/liaison/liaison?source=route',
        })
      });
      return;
    };
    let params = {
      orderKey: data['carTypeList'][data['carTypeIdx']]['orderKey'],
      chooseTime: data['date'],
      shiftTime: data['time'],
      contactId: data['liaison']['id'],
      placards: data['placards'],
      rideNumber: data['rideNumber'],
      flightNumber: data['flightNumber'],
      memo: data['memo']
    }
    data['coupon'] && (params['coupon'] = data['coupon']['id']);
    data['coupon'] && (params['userCouponId'] = data['coupon']['userCouponId']);
    service.getConnect(service.api.submitAirportRouteOrder, params).then(function (res) {
      wx.hideLoading();
      that.doWxPay(res.data)
    });
  },

  // 调起微信支付
  doWxPay(e) {
    var that = this;
    if(e.appId){
      wx.requestPayment({
        timeStamp: e.timeStamp,
        nonceStr: e.nonceStr,
        package: e.package,
        signType: e.signType,
        paySign: e.paySign,
        success(res) {
          console.log(res);
          wx.showToast({
            title: '支付成功~',
            mask: true
          })
          wx.showLoading({
            title: '请稍后...',
            mask: true
          });
          that.checkPayStatus(e.orderSn);
        },
        fail(res) {
          console.log(res);
          wx.navigateTo({
            url: '/pages/order/details/details?orderSn=' + e.orderSn,
          })
          // app.showConfirm('提示', '支付失败,是否前往订单页', true, function () {
          //   wx.navigateTo({
          //     url: '/pages/order/details/details?orderSn=' + e.orderSn,
          //   })
          // }, function () {
          //   that.loadData();
          // });
        }
      })
    } else {
      wx.showToast({
        title: '支付成功~',
        mask: true
      })
      that.checkPayStatus(e.orderSn);
    }
  },

  checkPayStatus(orderSn) {
    var that = this;
    service.getConnect(service.api.checkOrderPayStatus, { orderSn: orderSn }).then(function (res) {
      console.log(res);
      wx.hideLoading();
      if (res.data.isPay === 1) {
        // 跳转订单详情
        // wx.redirectTo({
        //   url: '/pages/order/details/details?orderSn=' + orderSn,
        // })
        // 跳转支付结果
        wx.navigateTo({
          url: '/pages/order/payResult/index?orderSn=' + orderSn,
        })
      } else {
        setTimeout(function () {
          that.checkPayStatus(orderSn);
        }, 1000);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    app.pageOnloadInit(this, app);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadData();
    this.loadCarListAndPriceByParams();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let wxappStyle = wx.getStorageSync('wxappStyle');
    return {
      title: app.globalData['wxappStyle']['wxappTitle'] || wxappStyle['wxappTitle'],
      path: '/pages/index/index'
    }

  }
})
